import {
  imgLoad
} from './utils';

//专门处理图片状态的类
export default class Lazyimg {
  //src 
  /**
   * 
   * @param {*} el 节点
   * @param {*} src 有loading 和 error
   * @param {*} options 用户配置项
   * @param {*} imgRender Lazy类定义的方法处理
   */
  constructor({
    el,
    src,
    options,
    imgRender
  }) {
    this.el = el;
    this.src = src;
    this.options = options;
    this.imgRender = imgRender;
    //图片是否加载完毕的flag
    this.loaded = false;
    this.state = {
      loading: false,
      error: false
    }
  }

  checkIsVisible() {
    //获取当前图片元素到页面顶端的距离
    const {
      top
    } = this.el.getBoundingClientRect();
    // console.log(top);
    //5 / 105 / 305 ....

    //用户设置的预加载图片区域 preload默认为1.3倍
    return top < window.innerHeight * (this.options.preload || 1.3);
  }

  laodImg() {
    // 设置 loading
    this.imgRender(this, 'loading');

    imgLoad(this.src).then(() => {
      this.state.loading = true;
      this.imgRender(this, 'ok');
      this.loaded = true;
    }, () => {
      this.state.error = true;
      this.imgRender(this, 'error');
      this.loaded = true;
    })
  }
}